<template>
<div class="chargebackInfo info-block" v-if="apply">
  <div class="info-header">
    <div class="info-status">{{'当前订单状态：' + generateOrderStatus(apply.status, true) + (apply.status === 5 ? '【等待客户发货】' : '')}}</div>
    <div class="info-button">
      <template v-if="apply.status === 0">
      <!--待处理-->
        <el-button size="mini" @click="showOper('REFUSE')">拒绝申请</el-button>
        <el-button type="primary" size="mini" @click="showOper('AGREE')">同意申请</el-button>
      </template>
      <template v-if="apply.status === 10">
        <!--处理中-->
        <el-button type="primary" size="mini" @click="showOper('RECEIVE')">确认收货</el-button>
      </template>
      <template v-if="apply.status === 15">
        <!--处理中-->
        <el-button size="mini" @click="showOper('REFUSE_ALL')">拒绝退款</el-button>
        <el-popconfirm
          :title="`本次售后服务共计返还礼金卡${apply.giftCardAmount}元，退款${generateDefaultMoney()}元。如使用换购券，则换购券返还。是否确认退款？`"
          @confirm="refund">
          <el-button slot="reference" type="primary" size="mini">确认退款</el-button>
        </el-popconfirm>
<!--        <el-button type="primary" size="mini" @click="showOper('HANDLE')">完成凭证上传</el-button>-->
      </template>
      <template v-if="5 <= apply.status && apply.status <= 15">
        <!--    可退款    -->
        <el-button size="mini" type="primary" @click="moneyForms.model.money = generateDefaultMoney();moneyForms.show = true">修改退款金额</el-button>
      </template>
      <el-divider v-if="!isBeforeComplete" direction="vertical" class="btn-divider"></el-divider>
      <template v-if="!isComplete">
        <el-button v-if="isBeforeComplete" type="primary" size="mini" @click="showOper('FINISH')">关闭售后</el-button>
        <el-popconfirm
          v-else
          title="您将在未退款的情况下强制关闭售后，此操作不可逆，请谨慎操作！"
          @confirm="showOper('FINISH')">
          <el-button slot="reference" type="danger" size="mini">关闭售后</el-button>
        </el-popconfirm>
      </template>
    </div>
  </div>
  <div class="info-content">
    <div class="info-item"
       v-for="(item, index) in templateArray"
       :key="index">
      <div class="info-item-header el-icon-medal">
        {{item.name}}
      </div>
      <y-table
        v-if="item.type === 'table'"
        border
        :getDataWay="{ data: item.model }"
        :columns="item.columns">
      </y-table>
      <el-descriptions :column="item.column || 3" direction="vertical" border v-else>
        <el-descriptions-item
            v-for="(item2, index2) in item.columns"
            :key="index + '_' + index2"
            :span="item2.span || 1">
          <template slot="label">
            {{item2.label}}
          </template>
          <span v-if="!item2.type">
            {{ generateDisplay(item2, item.model) }}
          </span>
          <el-image
            v-else-if="item2.type === 'img' && item.model[item2.prop]"
            v-for="url in item.model[item2.prop].split(',')"
            :key="url"
            style="height: 100px; width: 100px"
            fit="contain"
            :src="generateMediaUrl({ fileOpenUrl: url })"
            :preview-src-list="item.model[item2.prop].split(',').map(u => generateMediaUrl({ fileOpenUrl: u }))">
          </el-image>
          <div
            class="edit-img"
            v-else-if="item2.type === 'edit-img'"
            v-for="(attachment) in item.model[item2.prop]"
            :key="attachment.id">
            <span class="el-icon-delete" @click="delProof(attachment.id)"></span>
            <el-image
              style="height: 100px; width: 100px"
              fit="contain"
              :src="generateMediaUrl({ fileOpenUrl: attachment.fileOpenUrl })"
              :preview-src-list="item.model[item2.prop].map(u => generateMediaUrl({ fileOpenUrl: u }))">
            </el-image>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
  <y-form
    v-model="moneyForms.model"
    :visible.sync="moneyForms.show"
    title="修改退款金额"
    append-to-body
    width="900px"
    :form-attrs="moneyForms.formAttrs"
    :columns="moneyFormColumns"
    @open="moneyForms.model.note = '';moneyForms.model.money = generateDefaultMoney()"
    @closed="moneyForms.model.note = '';moneyForms.model.money = generateDefaultMoney()"
    @ensure="changeMoney">
  </y-form>
  <y-form
    v-model="operForms.model"
    :visible.sync="operForms.show"
    :title="operForms.typeTitle[operForms.type]"
    append-to-body
    width="900px"
    :form-attrs="operForms.formAttrs"
    :columns="operForms.formColumns"
    @open="operForms.model.reason = ''"
    @closed="operForms.model.reason = ''"
    @ensure="ensureModel">
  </y-form>
</div>
</template>

<script>
export default {
  name: "chargebackInfo",
  inject: ['getEnum', 'generateMediaUrl', 'defaultUploadChange'],
  props:{
    chargebackId: String
  },
  computed:{
    isComplete(){
      return !!this.apply.finishTime;
    },
    isBeforeComplete(){//是否是可以直接点击【结束售后】而不用提示的步骤
      return [20,30,35].includes(this.apply.status);
    },
    templateArray(){
      let ary = [
        {
          name: '退单信息',
          model: this.apply,
          column: 4,
          columns: [
            {
              label: '订单号',
              prop: 'orderSn'
            },
            {
              label: '退单人',
              prop: 'memberName'
            },
            {
              label: '退款方式',
              prop: 'applyType',
              formatter: (function(row){
                return this.$$getCommonArrayName(row.applyType, this.returnApplyTypeOptions)
              }).bind(this)
            },
            {
              label: '申请时间',
              prop: 'commitTime',
              formatter(row){
                return (row.commitTime || '').replace('T', ' ');
              }
            },
            {
              label: '订单项数量',
              prop: 'orderItemQuantity'
            },
            {
              label: '退货数量',
              prop: 'orderItemQuantity'
            },
            {
              label: '退货原因',
              prop: 'reason',
              formatter(row){
                return row.reason + '： ' + (row.note || '')
              }
            },
            {
              label: '退款金额(元)',
              prop: 'returnAmount',
              formatter: this.generateDefaultMoney
            },
            {
              label: '退货凭证',
              prop: 'proofPics',
              type: 'img',
              span: 4
            }
          ]
        },
        {
          name: '商品信息',
          model: this.apply,
          column: 5,
          columns:[
            {
              label: '商品名称',
              prop: 'productName'
            },
            {
              label: '商品图片',
              prop: 'productPic',
              type: 'img',
              span: 3
            },
            {
              label: '商品规格',
              prop: 'productSpec'
            },
            {
              label: '商品价格(元)',
              prop: 'productPerPrice',
              formatter(row){
                return row.productPerPrice + ' * ' + row.orderItemQuantity
              }
            },
            {
              label: '运费(元)',
              prop: 'deliveryFee',
              formatter(row){
                return '+' + (row.deliveryFee || 0);
              }
            },
            {
              label: '优惠(元)',
              prop: 'discountTotalPrice',
              formatter(row){
                return '-' + (row.discountTotalPrice || 0);
              }
            },
            {
              label: '礼金卡消费(元)',
              prop: 'giftCardAmount',
              formatter(row){
                return '-' + (row.giftCardAmount || 0);
              }
            },
            {
              label: '可退金额(元)',
              prop: 'productRealPrice'
            }
          ]
        }
      ];
      if(this.apply && this.apply.status >= 5){
        //客户已发货
        ary.push({
          name: '收货信息',
          model: this.apply,
          columns: [
            {
              label: '物流单号',
              prop: 'deliverySn'
            },
            {
              label: '物流公司',
              prop: 'deliveryCompany'
            },
            {
              label: '收货人',
              prop: 'receiveName'
            },
            {
              label: '收货电话',
              prop: 'receivePhone'
            },
            {
              label: '收货地址',
              formatter(row){
                return row.receiveProvince ? `${row.receiveProvince},${row.receiveCity},${row.receiveRegion}  ${row.receiveDetailAddress}` : '无'
              },
              span: 2
            }
          ]
        })
      }
      if(this.apply && this.apply.handleNote){
        ary.push({
          name: '最近的退款金额修改信息',
          model: this.apply,
          columns: [
            {
              label: '修改人',
              prop: 'handleMan'
            },
            {
              label: '修改信息',
              prop: 'handleNote'
            },
            {
              label: '修改时间',
              prop: 'handleTime',
              formatter(row){
                return (row.handleTime || '').replace('T', ' ');
              }
            }
          ]
        })
      }
      if(this.operateHistory && this.operateHistory){
        ary.push({
          name: '操作日志',
          type: 'table',
          model: this.operateHistory,
          columns: [
            {
              label: '操作人',
              prop: 'updateUserName'
            },
            {
              label: '退单状态',
              prop: 'status',
              formatter: (function(row){
                return this.generateOrderStatus(row.status);
              }).bind(this)
            },
            {
              label: '操作备注',
              prop: 'note'
            },
            {
              label: '操作时间',
              prop: 'updateTime',
              formatter(row){
                return (row.updateTime || '').replace('T', ' ');
              }
            }
          ]
        })
      }
      return ary
    },
    moneyFormColumns(){
      return [
        {
          label: "退款金额(元)",
          prop: "money",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              step: 0.01,
              min: 0,
              max: this.generateDefaultMaxMoney()
            }
          }
        },
        {
          label: "备注",
          prop: "note",
          rules: [{required: true, message: "请输入修改退款金额的备注", trigger: "blur"}],
          comp:{
            compType: 'input',
            attrs:{
              type: 'textarea',
              maxlength: 100,
              showWordLimit: true,
              autosize: {
                minRows: 3
              }
            }
          }
        }
      ]
    }
  },
  data() {
    return {
      returnOrderStatusOptions: this.getEnum('returnOrderStatus'),
      returnApplyTypeOptions: this.getEnum('returnApplyType'),
      operForms:{
        type: '',
        typeTitle: {
          'AGREE': '同意申请',
          'REFUSE': '拒绝申请',
          'RECEIVE': '确认收货',
          'REFUSE_ALL': '拒绝退货退款',
          'HANDLE': '完成凭证上传',
          'FINISH': '关闭售后'
        },
        show: false,
        model:{
          reason: '',
        },
        formAttrs: {
          labelWidth: '100px',
        },
        formColumns:[
          {
            label: "备注",
            prop: "reason",
            comp:{
              compType: 'input',
              attrs:{
                type: 'textarea',
                autosize: {
                  minRows: 3
                }
              }
            }
          }
        ]
      },
      apply: null,
      operateHistory: null,
      proof: [],
      showMoney: false,
      moneyForms:{
        show: false,
        model:{
          money: '',
          note: ''
        },
        formAttrs: {
          labelWidth: '100px',
        },
      },
      isInit: true,
    }
  },
  created(){
    this.initAll();
  },
  methods:{
    initAll(){
      this.$yAxios({
        url: this.$api.goods.queryChargeBackApply,
        data:{
          id: this.chargebackId
        },
        loading: true
      }, info => {
        this.initApply(info);
        this.initOperateHistory(info);
        this.initProof(info);
        this.isInit = true;
      })
    },
    initApply(info){
      this.$set(this, 'apply', info.apply);
    },
    initOperateHistory(info){
      if(info.operateHistory){
        this.$set(this, 'operateHistory', info.operateHistory);
      }
    },
    initProof(info){
      if(info.proof){
        this.$set(this, 'proof', info.proof);
      }
    },
    generateOrderStatus(returnOrderStatus, timeReact){
      if(timeReact && this.isComplete || returnOrderStatus === 25) return '售后结束';
      return this.$$getCommonArrayName(returnOrderStatus, this.returnOrderStatusOptions)
    },
    generateDisplay(row, model){
      let str = model[row.prop];
      if(row.formatter){
        str = row.formatter(model);
      }
      if(!str && str !== 0){
        str = row.emptyText || '无';
      }
      return str;
    },
    showOper(type){
      this.operForms.type = type;
      this.operForms.show = true;
    },
    refund(){
      let data = {
        refundOrderId: this.chargebackId,
        extend: this.getEnum('refundType').REFUND_ALL.value, //退货退款
        orderType: this.getEnum('commonOrderType').MALL.value
      }
      this.$yAxios({
        url: this.$api.common.refund,
        data,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '成功退款'
        });
        this.initAll();
      })
    },
    changeMoney(form){
      this.$yAxios({
        url: this.$api.goods.changeMoneyChargeBackApply,
        data:{
          id: this.chargebackId,
          money: form.money,
          note: form.note
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '修改金额成功'
        });
        this.initAll();
      })
    },
    generateDefaultMoney(){
      if(!this.apply) return 0;
      if(!this.apply.returnAmount && this.apply.returnAmount !== 0){
        return this.generateDefaultMaxMoney();
      }else{
        return this.apply.returnAmount
      }
    },
    generateDefaultMaxMoney(){
      if(!this.apply) return 0;
      return this.apply.productRealPrice || 0;
    },
    delProof(id){
      this.$yAxios({
        url: this.$api.common.removeAttachment,
        data:{
          id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.initAll();
      })
    },
    onUploadChange(fileObj){
      this.defaultUploadChange(Object.assign({
        businessId: this.apply.id,
        businessSysModuleCode: 'RETURN_APPLY_MANAGE'
      }, fileObj), info => {
        this.$message({
          type: 'success',
          message: '上传成功'
        });
        this.initAll();
      })
    },
    ensureModel(form){
      let param = {
        id: this.apply.id,
        note: form.reason
      }, url;
      if(this.operForms.type === 'AGREE'){
        url = this.apply.applyType === 1 ? this.$api.goods.agreeRefundChargeBackApply : this.$api.goods.agreeChargeBackApply;
      }else if(this.operForms.type === 'REFUSE' || this.operForms.type === 'REFUSE_ALL'){
        url = this.$api.goods.refuseChargeBackApply;
      }else if(this.operForms.type === 'RECEIVE'){
        url = this.$api.goods.receiveChargeBackApply;
      }else if(this.operForms.type === 'HANDLE'){
        url = this.$api.goods.handleChargeBackApply;
      }else if(this.operForms.type === 'FINISH'){
        url = this.$api.goods.finishChargeBackApply;
      }else return;
      this.$yAxios({
        url,
        data: param,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '处理成功'
        });
        this.initAll();
      })
    }
  }
}
</script>

<style scoped lang="less">
.chargebackInfo{
  width: 100%;
  height: 100%;
  padding: 20px 20px 0;
  /deep/.edit-img{
    position: relative;
    display: inline-block;
    >span{
      position: absolute;
      right: 5px;
      top: 5px;
      width: 20px;
      height: 20px;
      line-height: 20px;
      cursor: pointer;
      z-index: 1;
      background: #fff;
    }
  }
}
</style>